import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { IncidentService } from '../incident.service';
import { NzMessageService, NzModalRef, NzModalService } from 'ng-zorro-antd';
import { BullySubjectService, NotificationService } from 'app/shared/service';
import { MESSAGE_CHANNEL, SELECT_OPTIONS, SYSTEM_EVENT } from 'app/app.constants';
import { EquipmentService } from 'app/pages/equipment-management/equipment.service';
import { PlanTemplateComponent } from '../plan-template/plan-template.component';
import { TranslateService } from '@ngx-translate/core';
import { Subject } from 'rxjs';
import { PlanMsgInfoComponent } from '../plan-msg-info/plan-msg-info.component';
import { PublicService } from 'app/public/public.service';
const domtoimage = require('dom-to-image');

@Component({
    selector: 'itmp-response-plan',
    templateUrl: './response-plan.component.html',
    styleUrls: ['./response-plan.component.css']
})
export class ResponsePlanComponent implements OnInit {
    @Output() changeTabPage = new EventEmitter();
    @Input() accessButton;
    @Input() eventType: SYSTEM_EVENT;
    @ViewChild(PlanMsgInfoComponent) msgInfo: PlanMsgInfoComponent;
    value = '';
    toolbarList = [{ className: 'icon-dingwei' }];
    totalEle: number;
    listOfData = [];
    listOfDisplayData = [];
    editingItem = [];
    queryId = null;
    previewImg = '';
    currentDisplayUrl = [];
    renderHeader: any = [
        {
            name: 'IP Index',
            key: null,
            value: 'IP Index'
        },
        {
            name: 'CMD ID',
            key: null,
            value: 'CMD ID'
        },
        {
            name: 'System',
            key: null,
            value: 'system'
        },
        {
            name: 'Equipment Id',
            key: null,
            value: 'Device Id'
        },
        {
            name: 'Command Content',
            key: null,
            value: 'Command Content'
        },
        {
            name: 'Action',
            key: null,
            value: 'action'
        },
        {
            name: 'Result',
            key: null,
            value: 'Result'
        }
    ];
    optionList = [{ label: 'Accept', value: 0 }, { label: 'Reject', value: 1 }];
    selectedValue = 0;
    pagination = {
        totalEle: 25,
        currentPage: 1,
        currentSize: 10,
        pageSize: 10
    };
    // systemList = ['VMS', '', '', '', '', '', '', '', '', '', '', '', 'TSC'];
    systemList = [{ name: 'VMS', value: '0' }, { name: 'Dispatch', value: '12' }];
    systemObj = { '0': 'VMS', '12': 'Dispatch' };
    executeStatusList = ['Unexecuted', 'Executing', 'Execute Successed', 'Execute Failed'];
    isEditing = false;
    isExecute = false;
    isDeleting = false;
    isLoadingOne = false;
    isAddingTaks = false;
    resListCon = null;
    confirmModal: NzModalRef;
    modalService: any;
    seleceData = {
        start_X_Coor: '',
        start_Y_Coor: ''
    };
    previewUrl = null;
    requestData = {
        width: '',
        height: ''
    };
    length = '';
    imgArr = [];
    param = {
        strBase64: []
    };
    start_X_Coor = '';
    start_Y_Coor = '';
    deviceList = []; // 设备列表
    dispatchOptions = [];
    colorObj = { 0: 'black', 1: 'red', 2: 'yellow', 3: 'green', 4: 'cyan', 5: 'blue', 6: 'magenta', 7: 'white', 8: 'orange', 9: 'amber' };
    firstDisplayMessage = null;
    firstPlanImgs = [];
    firstLoading = false;
    displayMsgList = [];
    bakEditItem = null;

    constructor(
        private incidentService: IncidentService,
        private message: NzMessageService,
        private modal: NzModalService,
        private bully: BullySubjectService,
        private msg: NotificationService,
        private eqt: EquipmentService,
        private translate: TranslateService,
        private pub: PublicService
    ) {}

    ngOnInit() {
        this.getDeviceList();
        const s = this.pub.getSelectOptionsList(SELECT_OPTIONS.PARTNER_TYPE);
        this.dispatchOptions = s.data || [];
    }

    getData(item) {
        this.start_X_Coor = item.start_X_Coor;
        this.start_Y_Coor = item.start_Y_Coor;
        this.queryId = item.ir_ID;
        this.getResponsePlan(this.queryId);
    }

    /**
     * generate system first plan preivewUrl
     * @param data
     * @param index
     * @returns
     */
    setDisplayMsg(data, index) {
        const detail = data.cmdDetail;
        const templates = data.vmsTemplate;
        try {
            const templatePages = templates.templatePages || [];
            const tempArr = detail.split('$');
            tempArr.shift();
            tempArr.length = templatePages.length;
            const texts = [],
                graphics = [];
            tempArr.forEach((item, i) => {
                // i 代表页数
                const arr1 = item.split('#');
                const picIds = arr1.length === 1 ? [] : arr1[0].split(';');
                const lineTexts = arr1.length === 1 ? arr1.split(';') : arr1[1].split(';');
                lineTexts.forEach((t, j) => {
                    // j 代表行数
                    const tplTextInfo = templatePages[i].templateTexts[j];
                    texts.push({
                        charSpacing: tplTextInfo.charSpacing + 'px',
                        font: (tplTextInfo.fontSize || 15) + 'px',
                        foreColor: this.colorObj[tplTextInfo.forColor] || 'white',
                        pageSeq: i + 1,
                        text: t,
                        textSeq: j + 1,
                        textAreaX: tplTextInfo.textAreaX,
                        textAreaY: tplTextInfo.textAreaY
                    });
                });

                picIds.forEach((p, j) => {
                    const tplGraphInfo = templatePages[i].templateGraphics[j];
                    graphics.push({
                        graphicAreaX: tplGraphInfo.graphicAreaX,
                        graphicAreaY: tplGraphInfo.graphicAreaY,
                        graphicSeq: j + 1,
                        pageSeq: i + 1,
                        vmsGraphic: {
                            width: 100,
                            height: 100,
                            url: `http://192.168.0.80:9001/vms/graphic/${p}.png`
                            // url: 'http://192.168.0.80:9001/vms/graphic/1613988118892.png',
                        }
                    });
                });
            });
            const tplPages = [];
            templatePages.forEach((t, i) => {
                tplPages.push({
                    pageSeq: i + 1,
                    graphics: graphics.filter(g => g.pageSeq === i + 1),
                    texts: texts.filter(txt => txt.pageSeq === i + 1),
                    templateGraphics: t.templateGraphics,
                    templateTexts: t.templateTexts
                });
            });
            this.displayMsgList.push({
                _index: index,
                _displayMessage: {
                    deviceConfig: templates.deviceConfig,
                    templateId: templates.templateId,
                    templatePages: tplPages,
                    category: { categoryId: null },
                    deviceInfo: {
                        width: templates.deviceConfig.width,
                        height: templates.deviceConfig.height
                    }
                }
            });
        } catch (error) {
            console.warn(error);
        }
    }

    getResponsePlan(item) {
        this.isEditing = false;
        const queryData = {
            condition: {
                ip_id: null,
                ir_id: item
            },
            pageNum: 1,
            pageSize: 10
        };
        const query = this.incidentService.getIncidentResponsePlanList(queryData);
        query.subscribe(
            (res: any) => {
                if (res.messagecode === '000000') {
                    const response = res.data.content;
                    this.listOfData = response;
                    this.pagination.totalEle = res.data.totolElements;
                    this.pagination.currentSize = res.data.numberOfElements;
                    this.resListCon = res;
                    response.forEach((element, i) => {
                        element.cmdList.forEach((data, idx) => {
                            this.length = element.cmdList.length;
                            data.isSingleEditing = false;
                            if (element.sysID === '0') {
                                data.type = data.deviceDetailInfo.deviceType;
                                this.requestData = {
                                    width: data.deviceDetailInfo.width + 'px',
                                    height: data.deviceDetailInfo.height + 'px'
                                };
                            }
                            this.seleceData = element;
                            this.seleceData.start_X_Coor = this.start_X_Coor;
                            this.seleceData.start_Y_Coor = this.start_Y_Coor;
                            if (data.previewUrl) {
                                this.previewUrl = data.previewUrl;
                            }
                            if (data.sysID === '12') {
                                const cmdDetail = (data.cmdDetail || '').split(',');
                                data._dispatchTarget = cmdDetail[0] || '1';
                                data._dispatchNum = cmdDetail[1] || 1;
                            } else {
                                data._dispatchTarget = '1';
                                data._dispatchNum = 1;
                            }

                            if (data.sysID === '0' && data.cmdDetail && data.vmsTemplate && !data.previewUrl) {
                                this.setDisplayMsg(data, idx);
                            }
                        });
                    });
                } else {
                    this.message.create('error', res.message);
                }
            },
            (error: any) => {}
        );
    }
    showDetail(item): void {
        this.changeTabPage.emit(item);
    }
    editItem(item, i, j) {
        if (!this.isEditing) {
            this.isEditing = true;
            item.isSingleEditing = true;
            this.bakEditItem = JSON.parse(JSON.stringify(item));
        }
    }
    deleteItem(item, i, j) {
        const queryData = item.cmdID;
        this.confirmModal = this.modal.confirm({
            nzTitle: 'Delete',
            nzContent: 'Do you want to delete this response plan',
            nzOnOk: () =>
                this.incidentService.deleteResponsePlan(queryData).subscribe(
                    (res: any) => {
                        if (res.messagecode === '000000') {
                            this.message.create('success', 'Delete success!');
                            this.getResponsePlan(this.queryId);
                            this.bakEditItem = null;
                        } else {
                            this.message.create('warning', 'Delete failed!');
                        }
                    },
                    (error: any) => {}
                )
        });
    }
    positioning(item) {
        if (!item) {
            this.msg.notify({ type: 'warning', path: 'Share.Toolbar.select_notify' });
            return;
        }
        const data = {
            type: 'incident-position',
            data: item
        };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, data);
    }
    saveEditItem() {
        const checkItem = this.listOfData[0].cmdList.find(item => item.isSingleEditing === true);
        if (checkItem.sysID === '0' && !checkItem.deviceID) {
            this.message.create('warning', 'Please select Equipment Id !');
            return;
        }
        this.modal.confirm({
            nzTitle: 'Save Response Plan',
            nzContent: '<p style="font-size:24px">Are you sure you want to save this Response Plan?</p>',
            nzOkText: 'OK',
            nzOnOk: () => {
                this.listOfData[0].cmdList.forEach(item => {
                    if (item.sysID === '12') {
                        item.cmdDetail = [item._dispatchTarget, item._dispatchNum].join(',');
                    }
                });
                const query = this.incidentService.updateResponsePlan(this.listOfData[0]);
                query.subscribe(
                    (res: any) => {
                        if (res.messagecode === '000000') {
                            this.message.create('success', 'Update success!');
                            this.getResponsePlan(this.queryId);
                            this.bakEditItem = null;
                        }
                        this.refreshStatus();
                    },
                    (error: any) => {
                        this.message.create('warning', 'Update failed!');
                        this.refreshStatus();
                    }
                );
            },
            nzCancelText: 'Cancel',
            nzOnCancel: () => {}
        });
        // const query = this.incidentService.updateResponsePlan(this.listOfData[0]);
        // query.subscribe(
        //     (res: any) => {
        //         if (res.messagecode === '000000') {
        //             this.message.create('success', 'Update success!');
        //             this.getResponsePlan(this.queryId);
        //         }
        //         this.refreshStatus();
        //     },
        //     (error: any) => {
        //         this.message.create('warning', 'Update failed!');
        //         this.refreshStatus();
        //     }
        // );
    }
    cancelEdit(): void {
        if (this.isAddingTaks) {
            const idx = this.listOfData[0].cmdList.length - 1;
            this.listOfData[0].cmdList.splice(idx, 1);
            this.isAddingTaks = false;
        } else if (this.isDeleting) {
            this.listOfData = this.resListCon.data.content;
        }
        this.refreshStatus();
    }
    refreshStatus() {
        this.isEditing = false;
        this.firstLoading = false;
        this.listOfData.forEach(element => {
            element.cmdList.forEach((data, idx) => {
                if (data.isSingleEditing && this.bakEditItem) {
                    data.sysID = this.bakEditItem.sysID;
                    data.deviceID = this.bakEditItem.deviceID;
                    data.previewUrl = this.bakEditItem.previewUrl;
                    data._dispatchTarget = this.bakEditItem._dispatchTarget;
                    data._dispatchNum = this.bakEditItem._dispatchNum;
                    data.action = this.bakEditItem.action;
                    this.bakEditItem = null;
                }
                data.isSingleEditing = false;
            });
        });
    }
    execute() {
        if (this.listOfData.length === 0) {
            this.message.create('warning', 'Please select a incident record!');
            return;
        }
        if (this.listOfData[0].ip_ID) {
            const queryData = this.listOfData[0].ip_ID;
            this.confirmModal = this.modal.confirm({
                nzTitle: 'Execute',
                nzContent: 'Do you want to excute this response plan',
                nzOnOk: () => this.middleChange()
            });
        } else {
            this.message.create('warning', 'Please select a incident record!');
        }
    }
    middleChange() {
        this.saveTo();
        /* 当数据返回有previewUrl时，不再转请求updateBase64 */
        // if (this.previewUrl) {
        //     this.saveTo();
        // } else {
        //     const dom = document.getElementsByClassName('location');
        //     this.imgArr = [];
        //     for (let i = 0; i < dom.length; i++) {
        //         this.domtoimage(dom[i], dom.length);
        //     }
        //     this.param.strBase64 = [];
        // }
    }

    updateResponsePlan() {
        const newData = this.listOfData[0];
        newData.cmdList.forEach((item, index) => {
            this.imgArr.forEach((value, idx) => {
                if (index === idx) {
                    item.previewUrl = value;
                }
            });
        });
        const query = this.incidentService.updateResponsePlan(newData);
        query.subscribe(
            (r: any) => {
                if (r.messagecode === '000000') {
                    this.message.create('success', 'Update success!');
                    this.getResponsePlan(this.queryId);
                }
                this.refreshStatus();
            },
            (error: any) => {
                this.message.create('warning', 'Update failed!');
                this.refreshStatus();
            }
        );
        this.saveTo();
    }
    // dom转换成图片
    domtoimage(el, length) {
        const newEle = el;
        newEle.style.backGround = 'black';
        newEle.style.fontSize = '24px';
        newEle.style.color = 'red';
        newEle.style.textAlign = 'left';
        newEle.style.wordBreak = 'break-all';
        // newEle.style.width = this.requestData.width + 'px';
        // newEle.style.height = this.requestData.height + 'px';
        el.style.border = 'none'; // 去除边框
        setTimeout(() => {
            domtoimage
                .toJpeg(newEle, { cacheBust: true })
                .then(dataUrl => {
                    const url = dataUrl.split(',')[1];
                    // const url = JSON.stringify(dataUrl.split(',')[1]);
                    this.param.strBase64.push(url);
                    if (this.param.strBase64.length === length) {
                        this.incidentService.uploadBase64(this.param).subscribe(res => {
                            if (res['messagecode'] === '000000') {
                                this.imgArr = res.data;
                                this.updateResponsePlan();
                            }
                        });
                    }
                })
                .catch(function(error) {
                    console.error('oops, something went wrong!', error);
                });
        }, 200);
    }
    saveTo() {
        const queryData = this.listOfData[0].ip_ID;
        this.incidentService.executeResponsePlan(queryData).subscribe(
            (res: any) => {
                if (res.messagecode === '000000') {
                    this.message.create('success', 'Response plan is executed!');
                    this.getData(this.listOfData[0]);
                } else {
                    // this.message.create('warning', res.message);
                }
            },
            (error: any) => {}
        );
    }
    currentPageDataChange(e): void {
        this.listOfDisplayData = e;
    }
    addTask() {
        if (!this.listOfData.length) {
            this.listOfData = [
                {
                    ir_ID: this.queryId,
                    ip_ID: '',
                    cmdList: []
                }
            ];
        }
        const lastCmdId = this.listOfData[0].cmdList.length
            ? this.listOfData[0].cmdList[this.listOfData[0].cmdList.length - 1].cmdID
            : 10000;
        const data = {
            ack: null,
            action: 0,
            cmdDetail: '', // 暂无设计response plan的指令格式
            cmdID: lastCmdId + 1,
            cmdStatus: null,
            deviceID: null,
            executeStatus: 0,
            ipId: this.listOfData[0].ip_ID,
            isSingleEditing: true,
            sysID: '0',
            _dispatchTarget: '1',
            _dispatchNum: 1
        };
        this.listOfData[0].cmdList.push(data);
        this.isEditing = true;
        this.isAddingTaks = true;
    }

    getDeviceList() {
        const params = {
            condition: { eqtType: '0' },
            exportType: null,
            pageNum: 1,
            pageSize: 5000
        };
        this.eqt.getEquipmentList(params).subscribe(res => {
            if (res.errCode === '000000') {
                this.deviceList = (res.content && res.content.content) || [];
            }
        });
    }

    handleSelect(data) {
        const tempTranslate = [
            { title: 'EquipmentManagement.EquipmentManagement.Edit' },
            { title: 'EquipmentManagement.EquipmentManagement.Save' },
            { title: 'EquipmentManagement.EquipmentManagement.Cancel' }
        ];
        tempTranslate.forEach(item => {
            this.translate.get(item.title).subscribe((res: string) => {
                item.title = res || '';
            });
        });

        const isBoolean = value => {
            return typeof value === 'boolean';
        };
        const that = this;

        const modalRef = this.modal.create({
            nzTitle: tempTranslate[0].title,
            nzContent: PlanTemplateComponent,
            nzComponentParams: {},
            nzWidth: 1300,
            nzFooter: [
                {
                    label: tempTranslate[2].title,
                    shape: 'default',
                    onClick: () => modalRef.destroy()
                },
                {
                    label: tempTranslate[1].title,
                    type: 'primary',
                    loading: false,
                    onClick(instance): void {
                        const sub = new Subject();
                        sub.subscribe((val: any) => {
                            if (isBoolean(val)) {
                                this.loading = val as boolean;
                            } else {
                                modalRef.destroy();
                                that.incidentService.uploadBase64({ strBase64: val.planImgs }).subscribe(res => {
                                    if (res['messagecode'] === '000000') {
                                        data.previewUrl = (res.data || []).join(',');
                                        // that.updateAllResponsePlan();
                                    }
                                });
                            }
                        });
                        instance.saveClick(sub);
                    }
                }
            ]
        });
    }

    doDomToImage(shouldUpdate = false) {
        if (!this.displayMsgList.length) {
            if (shouldUpdate) {
                this.firstLoading = false;
                this.firstPlanImgs = [];
                this.firstDisplayMessage = null;
                this.updateAllResponsePlan();
            }
            return;
        }
        this.firstLoading = true;
        this.firstDisplayMessage = this.displayMsgList.shift();
        this.firstPlanImgs = [];
        setTimeout(() => {
            this.handleDomToImage(this.msgInfo.viewpointRef.nativeElement, this.firstDisplayMessage._displayMessage.templatePages.length);
        }, 200);
    }

    /**
     * 更新所有计划
     */
    updateAllResponsePlan() {
        const query = this.incidentService.updateResponsePlan(this.listOfData[0]);
        query.subscribe(
            (r: any) => {
                if (r.messagecode === '000000') {
                    this.message.create('success', 'Update success!');
                    this.getResponsePlan(this.queryId);
                }
                this.refreshStatus();
            },
            (error: any) => {
                this.message.create('warning', 'Update failed!');
                this.refreshStatus();
            }
        );
    }

    /**
     * 系统生成的第一条信息，第一次需要主动生成图片
     * @param el
     * @param length ['http://192.168.0.80:9001/vms/graphic/1637655778600.png', 'http://192.168.0.80:9001/vms/graphic/1637655778680.png']
     */
    handleDomToImage(el, length) {
        el.style.border = 'none'; // 去除边框
        this.msgInfo.setShowPage(length - 1);
        setTimeout(() => {
            domtoimage
                .toJpeg(el, { cacheBust: true })
                .then(dataUrl => {
                    this.firstPlanImgs.push(dataUrl.split(',')[1]);
                    length--;
                    if (length > 0) {
                        this.handleDomToImage(el, length);
                    } else {
                        this.incidentService.uploadBase64({ strBase64: this.firstPlanImgs }).subscribe(res => {
                            if (res['messagecode'] === '000000') {
                                this.listOfData[0].cmdList[this.firstDisplayMessage._index].previewUrl = (res.data || []).join(',');
                                this.doDomToImage(true);
                            } else {
                                this.firstLoading = false;
                            }
                        });
                    }
                })
                .catch(error => {
                    console.error('oops, something went wrong!', error);
                    this.firstLoading = false;
                });
        }, 200);
    }

    handleTypeChange(e, data) {
        if (e !== '0') {
            data.deviceID = null;
        }
    }

    /**
     * device id不能有重复
     */
    handleDevChange(e, data) {
        const f = this.listOfData[0].cmdList.find(item => item.deviceID === e && item.cmdID !== data.cmdID);
        if (f) {
            this.message.create('warning', `Device ID can't be repeated!`);
            setTimeout(() => {
                data.deviceID = null;
            });
        }
    }
}
